package sculove.spring.framework.web;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import sculove.spring.framework.util.AuthUtil;
import sculove.spring.framework.util.Configuration;

/**
 * Servlet Filter implementation class SessionCheckFilter
 */
public class SessionCheckFilter implements Filter {
	private final Log logger = LogFactory.getLog(this.getClass());
	
	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		
		/*
		 * 1. check pass URL
		 */
		if(AuthUtil.isPassURL(httpRequest.getRequestURL().toString())) {
			if(logger.isInfoEnabled()) logger.info("▷▶ Unconditaional Pass : " + httpRequest.getRequestURL().toString() + " in SessionCheckFilter");
			chain.doFilter(request, response);
		} else {
			/*
			 * 2. check Login Session
			 */
			if(!AuthUtil.hasSession(httpRequest)) {	//실패
				if("ajax".equals(httpRequest.getHeader("DataHeader-Type"))) {	// AJAX일 경우에
					if(logger.isInfoEnabled()) logger.info("▷▶ Ajax No Session : " + httpRequest.getRequestURL().toString() + " in SessionCheckFilter");
					httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN);
				} else {		// JSP인 경우
					if(logger.isInfoEnabled()) logger.info("▷▶ JSP No Session : " + httpRequest.getRequestURL().toString() + " in SessionCheckFilter");
					RequestDispatcher dispatcher = request.getRequestDispatcher(Configuration.getPropInstance().getString("com.session.forward-page"));
					dispatcher.forward(request, response);
				}
			} else {	//정상
				chain.doFilter(request, response);
			}
		}
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	@Override
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}
	
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
	}
}
